package model;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.vandorenmes.argus.R;

import controller.App;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class WCFconnection extends AsyncTask<String, String, String>
{

	private static String BASE_URL = "http://192.168.30.231:1111/get/";
	
	private Handler handler;
	private Context context;
	
	private WCFBehaviour wcfBehaviour;
	
	public WCFconnection(Handler handler, Context context)
	{
		this.handler = handler;
		this.context = context;
	}
	
	@Override
    protected String doInBackground(String... uri)
    {
		Log.v("wcf", "DoInBackground() - " + uri[0]);
		
		Message message = Message.obtain(handler, R.id.loading);
		message.sendToTarget();
		
		String url = BASE_URL + uri[0];
		
        try
        {
        	return createConnectionToService(url);
        }
        catch (Exception e)
        {
        	Log.v("wcf", "doInBackground exception" );        		
        	
			Bundle bundle = new Bundle();
			bundle.putString(CaptureHandler.DECODED_DATA, "Connection to Service failed");
			
			Message failMessage = Message.obtain(handler, R.id.WCFresponse_failed);	
			failMessage.setData(bundle);
			failMessage.sendToTarget(); 
        }
        
        return null;
    }
	
	private String createConnectionToService(String url) throws Exception
	{
    	HttpClient httpClient = new DefaultHttpClient();
        String responseString = null;
    	HttpGet getter = new HttpGet(url);
    	HttpResponse response = httpClient.execute(getter);

        StatusLine statusLine = response.getStatusLine();
        
        boolean connectionStatusIsEqualToOK = statusLine.getStatusCode() == HttpStatus.SC_OK;
        
        if(connectionStatusIsEqualToOK)
        {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            responseString = out.toString();
            
            //Check contentType of header
            //if(response.getEntity().getContentType().getValue().equals("application/json"))
            	wcfBehaviour = new JsonBehaviour();
            
            out.close();
            Log.v("wcf", "wcf response received: " + responseString);
            return responseString;
        } 
        else
        {
            //Close connection
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
	}
	
	@Override
    protected void onPostExecute(String result)
	{
		if(result != null)
		{
			Activity activity = (Activity) context;
			App app = (App) activity.getApplication();
			app.setMachines(wcfBehaviour.translateResponseToMachine(result));
				
			Log.v("wcf", "wcf onPostExecute: " + result);
			Log.v("wcf", context.toString());
			Log.v("wcf", activity.toString());
			
			Message message = Message.obtain(handler, R.id.WCFresponse_received);		
			message.sendToTarget();
		}
		else
			Log.e("wcf", "OnPostExecute() - NULL!!!");
    }
	
}